const hre = require("hardhat");

async function main() {
  console.log("Deploying XLayerLaunchPad contract...");

  const networkName = hre.network.name;
  console.log("Deploying to network:", networkName);

  // Allow override via env
  const envRouter = process.env.ROUTER_ADDRESS;
  const DEX_ROUTER_MAINNET = envRouter || "0x5A77f1443D16ee5761d310e38b62f77f726bC71c";
  const DEX_ROUTER_TESTNET = envRouter || "0x5A77f1443D16ee5761d310e38b62f77f726bC71c";

  let dexRouter;
  if (networkName === "xlayer") {
    dexRouter = DEX_ROUTER_MAINNET;
  } else if (networkName === "xlayerTestnet") {
    dexRouter = DEX_ROUTER_TESTNET;
  } else {
    dexRouter = DEX_ROUTER_TESTNET; // default fallback
  }

  // Check if router has code; if not and DEPLOY_MOCKS=1 then deploy mocks
  const code = await hre.ethers.provider.getCode(dexRouter);
  if (code === "0x") {
    console.log("Warning: No contract code at router address:", dexRouter);
    if (process.env.DEPLOY_MOCKS === '1') {
      console.log("DEPLOY_MOCKS=1 -> deploying MockWETH, MockFactory, MockRouter on-chain...");
      const MockWETH = await hre.ethers.getContractFactory("MockWETH");
      const mockWETH = await MockWETH.deploy();
      await mockWETH.waitForDeployment();
      console.log("MockWETH:", await mockWETH.getAddress());

      const MockFactory = await hre.ethers.getContractFactory("MockFactory");
      const mockFactory = await MockFactory.deploy();
      await mockFactory.waitForDeployment();
      console.log("MockFactory:", await mockFactory.getAddress());

      const MockRouter = await hre.ethers.getContractFactory("MockRouter");
      const mockRouter = await MockRouter.deploy(await mockWETH.getAddress(), await mockFactory.getAddress());
      await mockRouter.waitForDeployment();
      dexRouter = await mockRouter.getAddress();
      console.log("MockRouter:", dexRouter);
    } else {
      console.log("Set a valid ROUTER_ADDRESS or export DEPLOY_MOCKS=1 to deploy mock router.");
      throw new Error("Router address has no code");
    }
  }

  console.log("Using DEX Router:", dexRouter);

  const XLayerLaunchPad = await hre.ethers.getContractFactory("XLayerLaunchPad");
  const launchPad = await XLayerLaunchPad.deploy(dexRouter);
  await launchPad.waitForDeployment();
  const launchPadAddress = await launchPad.getAddress();
  const deployTx = launchPad.deploymentTransaction();

  console.log("XLayerLaunchPad deployed to:", launchPadAddress);
  console.log("Transaction hash:", deployTx.hash);

  if (networkName !== "hardhat" && deployTx) {
    console.log("Waiting for 3 confirmations...");
    await deployTx.wait(3);
    console.log("Confirmed.");
    if ((networkName === 'xlayer' || networkName === 'xlayerTestnet') && process.env.XLAYER_API_KEY) {
      try {
        console.log("Verifying...");
        await hre.run("verify:verify", { address: launchPad.address, constructorArguments: [dexRouter] });
        console.log("Verified successfully.");
      } catch (e) {
        console.log("Verification skipped/failed:", e.message);
      }
    }
  }

  console.log("\n=== Deployment Summary ===");
  console.log("Network:", networkName);
  console.log("LaunchPad:", launchPadAddress);
  console.log("Router:", dexRouter);
  console.log("Deployer:", await (await hre.ethers.getSigners())[0].getAddress());
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });